//
//  goldViewController.swift
//  NewLndd
//
//  Created by 邵禹曦 on 2020/1/8.
//  Copyright © 2020 辽宁当代. All rights reserved.
//

import UIKit
import SwiftyJSON
// MARK: - 出金
class goldViewController: ApiViewController, UITableViewDelegate,UITableViewDataSource {

    var mode = ZZDatePicker.ZZDatePickerMode.default
    @IBOutlet weak var TableView: UITableView!
    // 单选默认
    var bank : String = "1"
    var _comInfo : String?
    @IBOutlet weak var kczj: UILabel! // 可出资金
    @IBOutlet weak var cjxt: UITextField!// 出金系统
    @IBOutlet weak var cj: UITextField!//出金金额
    @IBOutlet weak var yhkmm: UITextField! // 银行卡密码
    @IBOutlet weak var zzmm: UITextField! // 资金密码
    
    
    @IBOutlet weak var paBtn: DLRadioButton! // 平安
    @IBOutlet weak var gdBtn: DLRadioButton! // 光大
    @IBOutlet weak var czBtn: UIButton!// 重置
    @IBOutlet weak var tjBtn: UIButton!//提交
    
    @IBOutlet weak var startTime: UITextField!
    @IBOutlet weak var endTime: UITextField!
    @IBOutlet weak var cx: UIButton!// 查询
    var BKID : String? // 银行id
    var ssr : String? // 所属人查询
    
    // 定义数组  Use of undeclared type 'Status'  数组 : [模型Model]
    private lazy var ViewModels : [gold] = [gold]()
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 结束日期
        endTime.text = nowTime("yyyy-MM-dd HH:mm:ss")
        let tdata = nowTime("yyyy-MM-dd")
        // 开始日期
        startTime.text = getLastDay(tdata)
        cjxt.text = "挂牌交易系统"
        showInfo()
        // 出金
        bankInfo()

    }
    


}

extension goldViewController {
    private func showInfo() {
        paBtn.addTarget(self, action: #selector(mrBtnClick), for: .touchUpInside)
        gdBtn.addTarget(self, action: #selector(mcBtnClick), for: .touchUpInside)
        cx.addTarget(self, action: #selector(cxBtnClick), for: .touchUpInside)
        startTime.addTarget(self, action: #selector(selectDate(_:)), for: .touchDown)
        endTime.addTarget(self, action: #selector(selectDate(_:)), for: .touchDown)
        // GCD
        let group = DispatchGroup()
    
        // 从沙盒中获取参数
        var userPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
        userPath =  (userPath as NSString).appendingPathComponent("data.plist")
        user = NSKeyedUnarchiver.unarchiveObject(withFile: userPath) as? User
        Thread.sleep(forTimeInterval: 0.05)

        // 用户验证
        self.u = user?.U!
        self.retcode = user?.RETCODE!
        // 用户验证
        let str = [u,"101",retcode]
            
        //self.isLogin = self.crj_network(str: str as! [String], group: group)
        group.enter()
        NetworkTools.share.check_user(code: str as Array<Any>) { (result, error) in
                      
                          if error != nil {
                              print("no no no")
                              return
                          }
                          

                          if Int(self._retcode(res: result!))! < 0 {
                              self.isLogin = false
                          } else {
                              self.isLogin = true
                          }
                          group.leave()
                      }

        group.notify(queue: DispatchQueue.main) {
            if !self.isLogin {
                if #available(iOS 13.0, *) {
                    self._alertVisitorView()
                }
                return
            } else {
                // 2.设置导航栏内容
                self.tableShouInfo(startTime: self.startTime.text!, endTime: self.endTime.text!)
            }
        }
    }
    // 查询
    @objc private func cxBtnClick() {
        self.tableShouInfo(startTime: self.startTime.text!, endTime: self.endTime.text!)
    }
    @objc private func mrBtnClick() {
        self.bank = "1"
    }
    
    @objc private func mcBtnClick() {
        self.bank = "2"
    }
    
    @objc func selectDate(_ btn: UITextField) {
        ZZDatePicker.show(self, mode: mode) { [weak self] (date) in
            self?.mode.date = date
            let fmt = DateFormatter()
            fmt.dateFormat = "yyyy-MM-dd HH:mm:ss"
            btn.text = fmt.string(from: date)
        }
    }
    
    
}


extension goldViewController {
    // MARK: - TableViewShowInfo
    @objc private func tableShouInfo(startTime : String ,endTime : String ) {
        
        let str = [user?.U!,user?.RETCODE! , startTime,endTime,"20","-1","ALL","-100","0"]
        Thread.sleep(forTimeInterval: 0.05)
        NetworkTools.share.m_inout_fundsflow_query(code: str as Array<Any>) { (result, error) in
            
            if error != nil {
                print("no no no")
                return
            }
            

            
            // 获取可选类型中的数组
            guard let resultArray = result else {
                print("no")
                return
            }
            //print(resultArray)
            
            if let REP = resultArray["REP"] as? [String : AnyObject] {
                if let resultList = REP["RESULTLIST"] as? [String : AnyObject] {
                    for arrTempDict in resultList {
                        for temp in arrTempDict.value as! NSArray {
                            let sta = gold(dict: temp as! [String : AnyObject])
                            self.ViewModels.append(sta)
                        }
                    }
                    // 刷新表格
                    self.TableView.reloadData()
                }
            }
            
            
        }
        
        
    }
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.ViewModels.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell : goldViewCell = tableView.dequeueReusableCell(withIdentifier: "goldViewCellid") as! goldViewCell
        cell.ViewModel = ViewModels[indexPath.row]
        return cell
    }
    
    // cell高
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 204
    }
}



extension goldViewController {
    // MARK: 获取当前时间
    // 这里的 type 是指日期的格式 “yyyyMMdd” 或者 “yyyy-MM-dd” 这样子
    func nowTime(_ type: String?) -> String {
        let currentDate = Date()
        let formatter = DateFormatter()
        formatter.dateFormat = type ?? "yyyyMMdd"
        let time = formatter.string(from: currentDate)
        return time
    }
    
    // MARK: 前一天的时间
    // nowDay 是传入的需要计算的日期
    func getLastDay(_ nowDay: String) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
            
        // 先把传入的时间转为 date
        //let date = dateFormatter.date(from: nowDay)
        let date = dateFormatter.date(from: nowDay)
        let lastTime: TimeInterval = -(24*60*60) // 往前减去一天的秒数，昨天
    //        let nextTime: TimeInterval = 24*60*60 // 这是后一天的时间，明天
            
        let lastDate = date?.addingTimeInterval(lastTime)
        let lastDay = dateFormatter.string(from: lastDate!) + " 00:00:00"
        return lastDay
    }
}


// MARK: - 获取出金信息
extension goldViewController {
    
    // 获取银行编号 banks_info_query
    @objc private func bankInfo() {
        let group = DispatchGroup()
        let str = [user?.U!,user?.RETCODE!]
        group.enter()
        NetworkTools.share.banks_info_query(code: str as Array<Any>) { (result, error) in
        
            if error != nil {
                print("no no no")
                return
            }
            
            // 获取可选类型中的数组
            guard let resultArray = result else {
                print("no")
                return
            }
       
            let rstJson = JSON(resultArray)
            self.BKID = (rstJson["REP"]["RESULTLIST"]["REC"][0]["BKID"].stringValue )
            group.leave()
        }
        group.notify(queue: DispatchQueue.main) {
            self.ssrInfo()
            
        }
        
        
    }
    
    // 所属人
    @objc private func ssrInfo() {
        let group = DispatchGroup()
        let str = [user?.U!,user?.RETCODE!]
        group.enter()
        NetworkTools.share.belonger_query(code: str as Array<Any>) { (result, error) in
        
            if error != nil {
                print("no no no")
                return
            }
            
            // 获取可选类型中的数组
            guard let resultArray = result else {
                print("no")
                return
            }
 
            let rstJson = JSON(resultArray)
            self.ssr = (rstJson["REP"]["RESULTLIST"]["REC"][0]["B"].stringValue )
            group.leave()
        }
        group.notify(queue: DispatchQueue.main) {
            self.tjBtn.addTarget(self, action: #selector(self.tjBtnClick), for: .touchUpInside)
            
        }
        
        
    }
    
    
    
    
    
    
    
    
    @objc private func tjBtnClick() {
    guard self.cj.text != "" else {
        if #available(iOS 13.0, *) {
            self.showMsgbox(_message: "出金金额不能为空")
        }
        return
    }
    
    guard self.yhkmm.text != "" else {
        if #available(iOS 13.0, *) {
            self.showMsgbox(_message: "银行卡密码不能为空")
        }
        return
    }
        
    guard self.zzmm.text != "" else {
            if #available(iOS 13.0, *) {
                self.showMsgbox(_message: "资金密码不能为空")
            }
            return
        }
        let _fcj = String(format: "%.2f", (self.cj.text)!)
    
        let str = [user?.U!,user?.RETCODE! ,self.zzmm.text!,self.BKID,"99",self.yhkmm.text! ,self.ssr, "1",_fcj]
        print(str)
    NetworkTools.share.out_funds(code: str as Array<Any>) { (result, error) in
        
        if error != nil {
            print("no no no")
            return
        }
        

        
        // 获取可选类型中的数组
        guard let resultArray = result else {
            print("no")
            return
        }
        
        
        print(resultArray)
        if let REP = resultArray["REP"] as? [String : AnyObject] {
            if let arr = REP["RESULT"] as? [String : AnyObject]   {
                let code : Int = Int(arr["RETCODE"] as! String)!
                if(Int(truncating: NSNumber(value: code)) > 0) {
                    if #available(iOS 13.0, *) {
                        self.showMsgbox(_message: "请求成功")
                    }
                } else {
                    if #available(iOS 13.0, *) {
                        self.showMsgbox(_message: "请求失败")
                    }
                }
            }
        }
        }
    
    }
}
